﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.DirectoryServices;
using System.Collections.Specialized;
using System.Configuration;

namespace UpdateSPUserProfileTimerJob
{
    public class UpdateSPUserProfileTimerJob : SPJobDefinition
    {
        public UpdateSPUserProfileTimerJob() : base() { }

        public UpdateSPUserProfileTimerJob(string jobName, SPWebApplication webApp)
            : base(jobName, webApp, null, SPJobLockType.Job)
        {
            this.Title = jobName;
        }
        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // Get the root site of the web application the timer sub is running on.
                    using (SPSite elevatedSite = new SPSite(this.WebApplication.Sites[0].Url))
                    {
                        // Reads from OWSTimer.Exe.Config File --Gets AD field for associated UserProfile Field
                        string hireDate = ConfigurationManager.AppSettings["HireDate"].ToString();
                        
                        if (!string.IsNullOrEmpty(hireDate))
                        {
                            SPServiceContext context = SPServiceContext.GetContext(elevatedSite);
                            HttpContext.Current = null;
                            UserProfileManager profileManager = new UserProfileManager(context);
                            foreach (UserProfile userProfile in profileManager)
                            {
                                string userName1 = userProfile["AccountName"].ToString();
                                string userName = userName1.Substring(userName1.IndexOf('\\') + 1).ToString();
                                DirectorySearcher ds = new DirectorySearcher();
                                ds.Filter = "samaccountname=" + userName;
                                SearchResult result = ds.FindOne();
                                if (result != null && userProfile["SPS-HireDate"].Value == null)
                                {
                                    try
                                    {
                                        // Get the hire date value from AD using the Hire Date AD Field Name.
                                        string hireDateValue = result.Properties[hireDate][0].ToString();
                                        if (!string.IsNullOrEmpty(hireDateValue))
                                        {
                                            //if (userProfile["SPS-HireDate"].Value == null)
                                            //{
                                                userProfile["SPS-HireDate"].Value = hireDateValue;
                                                userProfile.Commit();
                                            //}
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                                        diagSvc.WriteTrace(0, new SPDiagnosticsCategory("SPUserProfileUpdate", TraceSeverity.Monitorable, EventSeverity.Warning), TraceSeverity.Monitorable, "UpdateSPUserProfileTimer Job Failed :Hire Date invalid format or does not exist for user: " + userName);
                                        if (!System.Diagnostics.EventLog.SourceExists("SPUserProfileUpdate"))
                                            System.Diagnostics.EventLog.CreateEventSource("SPUserProfileUpdate", "Application");
                                        System.Diagnostics.EventLog.WriteEntry("SPUserProfileUpdate", "UpdateSPUserProfileTimer Job Failed : Hire Date invalid format or does not exist for user: " + userName, System.Diagnostics.EventLogEntryType.Warning);
                                    }
                                }
                            }
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                diagSvc.WriteTrace(0, new SPDiagnosticsCategory("SPUserProfileUpdate", TraceSeverity.Monitorable, EventSeverity.Warning), TraceSeverity.Monitorable, "UPdateSPUserProfileTimerJob Error: Profile update failed");
                if (!System.Diagnostics.EventLog.SourceExists("SPUserProfileUpdate"))
                    System.Diagnostics.EventLog.CreateEventSource("SPUserProfileUpdate", "Application");
                System.Diagnostics.EventLog.WriteEntry("SPUserProfileUpdate", "UPdateSPUserProfileTimerJob Error: Profile update failed. " + ex.Message, System.Diagnostics.EventLogEntryType.Warning);
            }
        }
    }
}

